import {
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { DeskService } from './desk.service';
import { Server, Socket } from 'socket.io';

@WebSocketGateway({ cors: { origin: '*' } })
export class DeskGateway {
  constructor(private readonly deskService: DeskService) {}

  @WebSocketServer() server: Server;
  @SubscribeMessage('create')
  create(client: Socket, uuid: string): void {
    client.join(uuid);
  }

  @SubscribeMessage('request')
  request(
    @MessageBody() payload: { from: string; to: string; code: string },
  ): void {
    const { from, to, code } = payload;

    this.server.to(to).emit('request', { from, code });
  }

  @SubscribeMessage('finish')
  finish(
    @MessageBody() payload: { from: string; to: string; code: string },
  ): void {
    const { from, to, code } = payload;

    this.server.to(to).emit('finish', { from, code });
  }

  @SubscribeMessage('reply')
  reply(
    @MessageBody()
    payload: {
      from: string;
      to: string;
      status: 'agree' | 'disagree' | 'controlled' | 'code-error';
      code?: string;
    },
  ): void {
    const { from, to, status, code } = payload;

    this.server.to(to).emit('reply', {
      from,
      status,
      code,
    });
  }

  @SubscribeMessage('offer')
  offer(
    @MessageBody()
    payload: {
      offer: any;
      from: string;
      to: string;
    },
  ): void {
    this.server.to(payload.to).emit('offer', payload);
  }

  @SubscribeMessage('answer')
  answer(
    @MessageBody()
    payload: {
      answer: any;
      from: string;
      to: string;
    },
  ): void {
    this.server.to(payload.to).emit('answer', payload);
  }

  @SubscribeMessage('candidate')
  candidate(
    @MessageBody()
    payload: {
      candidate: any;
      from: string;
      to: string;
    },
  ): void {
    this.server.to(payload.to).emit('candidate', payload);
  }

  @SubscribeMessage('leave')
  break(@MessageBody() payload: { from: string; to: string }): void {
    const { from, to } = payload;
    this.server.to(to).emit('leave', { from });
  }
}
